package org.jeecg.modules.carMoveCode.service.impl;

import cn.hutool.http.*;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.app.userSetting.entity.AppUserSetting;
import org.jeecg.modules.app.userSetting.service.AppUserSettingService;
import org.jeecg.modules.carMoveCode.service.CarMoveCodeService;
import org.jeecg.modules.system.entity.SysFiles;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysFilesService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @description: CAR MOVE CODE SERVICE IMPL
 * @author: zwf
 * @create: 2025-06-13 11:45
 **/
@Slf4j
@Service
public class CarMoveCodeServiceImpl implements CarMoveCodeService {
    @Value("${config.applet.sso}")
    private String SSO; // 小程序的 AppID
    @Value("${config.applet.version}")
    private String VERSION; // 小程序的 AppID
    @Value("${config.applet.appId}")
    private String APPID; // 小程序的 AppID
    @Value("${config.applet.appSecret}")
    private String APPSECRET; // 小程序的 AppSecret

    @Resource
    private ISysFilesService filesService;
    @Resource
    private ISysUserService userService;
    @Resource
    private AppUserSettingService userSettingService;


    /**
     * 创建挪车码
     *
     * @author zwf
     * @date created in 2025/5/12 9:34
     * @param: params
     * @return: org.jeecg.common.api.vo.Result<java.lang.String>
     */
    @Override
    public Result<String> create(JSONObject params) {

        try {
            String plateNumber = params.getString("plateNumber");
            String contact = params.getString("contact");
            String contactType = params.getString("contactType");

            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();


            SysUser user = userService.getById(sysUser.getId());
            AppUserSetting userSetting = userSettingService.getByUserId(sysUser.getId());

            if (userSetting.getPlateNumber() != null && !userSetting.getPlateNumber().isEmpty()) {
                // 判断联系方式是否被占用
                if ("1".equals(contactType)) {
                    SysUser userByPhone = userService.getUserByPhone(contact);
                    if (userByPhone != null) {
                        return Result.error("该手机号已被占用");
                    }
                    user.setPhone(contact);
                }
                if ("2".equals(contactType)) {
                    SysUser userByEmail = userService.getUserByEmail(contact);
                    if (userByEmail != null) {
                        return Result.error("该邮箱已被占用");
                    }
                    user.setEmail(contact);
                }

                userService.updateById(user);
                if (plateNumber.equals(userSetting.getPlateNumber())) {
                    LambdaQueryWrapper<SysFiles> query = new LambdaQueryWrapper<>();
                    query.eq(SysFiles::getCreateBy, sysUser.getId());
                    query.eq(SysFiles::getDelFlag, "0");
                    query.eq(SysFiles::getStoreType, "app-move");

                    SysFiles file = filesService.getOne(query);
                    if (file != null) {
                        return Result.ok(file.getUrl());
                    }
                } else {
                    userSetting.setPlateNumber(plateNumber);
                    userSetting.setUpdateTime(new Date());
                    userSetting.setUpdateBy(sysUser.getId());
                    userSetting.setRemindType(contactType);
                    userSettingService.updateById(userSetting);

                    QueryWrapper<SysFiles> query = new QueryWrapper<>();
                    query.eq("create_by", sysUser.getId());
                    query.eq("del_flag", "0");

                    List<SysFiles> files = filesService.list(query);
                    if (files != null && files.size() > 0) {
                        files.forEach(file -> {
                            file.setDelFlag("1");
                            file.setUpdateBy(sysUser.getId());
                            file.setUpdateTime(new Date());
                            filesService.updateById(file);
                        });
                    }
                }
            } else {
                userSetting.setPlateNumber(plateNumber);
                userSetting.setRemindType(contactType);
                userSettingService.saveOrUpdate(userSetting);
            }

            String unlimitedQRCode = getUnlimitedQRCode(sysUser);

            return Result.ok(unlimitedQRCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.error("none");
    }

    /**
     * 获取小程序 token
     *
     * @author zwf
     * @date created in 2025/5/12 10:54
     * @return: java.lang.String
     */
    private String getAccessToken() {
        String url = SSO + "/cgi-bin/token";

        String requestUrl = String.format("%s?appid=%s&secret=%s&grant_type=client_credential", url, APPID, APPSECRET);

        String response = HttpUtil.createRequest(Method.GET, requestUrl).execute().body();

        log.info("response:{}", response);

        JSONObject responseBody = JSONObject.parseObject(response);

        return responseBody.getString("access_token");
    }

    /**
     * 创建小程序码
     *
     * @author zwf
     * @date created in 2025/5/12 10:55
     * @param: token
     * @param: userId
     * @return: java.lang.String
     */
    private String getUnlimitedQRCode(LoginUser sysUser) {
        String fileUrl = "";
        try {
            String accessToken = getAccessToken();

            String url = SSO + "/wxa/getwxacodeunlimit";

            String requestUrl = String.format("%s?access_token=%s", url, accessToken);

            JSONObject params = new JSONObject();

            params.put("page", "pages/index/index");
            params.put("scene", sysUser.getId());
            params.put("check_path", false);
            params.put("env_version", VERSION);

            // 发起请求
            HttpResponse response = HttpRequest.post(requestUrl)
                    .contentType(ContentType.JSON.getValue())
                    .body(params.toString())
                    .execute();

            byte[] imageBytes = response.bodyBytes();
            if (imageBytes != null && imageBytes.length > 0) {
                InputStream stream = new ByteArrayInputStream(imageBytes);

                String fileName = sysUser.getId() + ".png";

                fileUrl = MinioUtil.upload(stream, "uqrc/" + fileName);

                if (fileUrl != null) {
                    SysFiles file = new SysFiles();

                    file.setFileName(fileName);
                    file.setUrl(fileUrl);
                    file.setFileType("image");
                    file.setStoreType("app-move");
                    file.setFileSize(imageBytes.length / 1024.0);
                    file.setDelFlag("0");
                    file.setCreateTime(new Date());
                    file.setCreateBy(sysUser.getId());

                    filesService.save(file);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileUrl;
    }
}
